//
//  MDDHomeViewController.m
//  com.modada.new
//
//  Created by ferver7 on 2019/3/9.
//  Copyright © 2019 ferver7. All rights reserved.
//

#import "MDDHomeViewController.h"
#import "HomeKindItem.h"
#import "HomeADItem.h"
#import "AppBaseGoodItem.h"
#import "HomeGoodItemCCell.h"
#import "MesageListViewController.h"
#import "GYRollingNoticeView.h"
#import "MDDGoodsDetailViewController.h"
#import "TouTiaoListViewController.h"
#import "MDDLoginViewController.h"
#import "WXWebviewController.h"
#import "MDDGoodsDetailViewController.h"
#import "StoreDetailViewController.h"
#import "MDDStoreViewController.h"
#import "LLSearchViewController.h"
#import "ReceiveCouponViewController.h"
#import "AppDelegate.h"
#import "AppPushHandleTool.h"

@interface MDDHomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,AxcBannerViewDataSource,AxcBannerViewDelegate,GYRollingNoticeViewDataSource, GYRollingNoticeViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *selfCollectionView;
@property (nonatomic, strong) AxcUI_BannerView *bannerView;
@property (nonatomic,strong) NSMutableArray *bannerList;
@property (nonatomic,strong) NSMutableArray *homeKindItems;
@property (nonatomic,strong) NSMutableArray *remomGoodItems;
@property (nonatomic,strong) GYRollingNoticeView *noticeView;
@property (nonatomic,strong) NSMutableArray *noticeArr;
@property (nonatomic,assign) NSInteger page;
@property (nonatomic,assign) BOOL hasPlantCoupon;
@end

@implementation MDDHomeViewController
-(void)leftAction:(UIButton *)sender
{
    
}
-(void)rightAction:(UIButton *)sender
{
    
    if ([[AppUserBaseModel sharedUserData].phone isEqualToString:@"13975856648"]) {//游客模式的判断
        [[NSNotificationCenter defaultCenter] postNotificationName:@"appUserOutLogin" object:nil];
        return;
    }
    
    MesageListViewController * mlvc = mGetStoryboardViewController(@"Main", @"mesageListViewController");
    NavigationController_pushVC(mlvc);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    mNavitationTitle(@"首页");
    self.page = 1;
    self.homeKindItems = [[NSMutableArray alloc]init];
    self.remomGoodItems = [[NSMutableArray alloc]init];
    [self loadHomeADdata];//请求首页广告
    [self loadHomeKinds];//请求首页分类数据
    [self loadHomeRemmendGoods];//请求首页推荐商品
    [self loadHomeOrderScroll];//查询首页订单信息
    [self loadHadCounpon];//查询是否有优惠券
    self.selfCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadHomeRemmendGoods];//请求首页推荐商品
        [self loadHomeOrderScroll];//查询首页订单信息
        [self loadHadCounpon];
    }];
    self.selfCollectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadHomeRemmendGoods];//请求首页推荐商品
    }];
    [self addRightBarButtonItemWithTitle:@"消息" withImage:mImageByName(@"消息") action:@selector(rightAction:)];
    [self addLeftBarButtonItemWithTitle:[AppUserBaseModel sharedUserData].county withImage:mImageByName(@"地址 (1)") action:@selector(leftAction:)];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(appOutLogin) name:@"appUserOutLogin" object:nil];
    
    UIView *navMiddleV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, mScreenWidth-140, 32)];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(searchAction)];
    [navMiddleV addGestureRecognizer:tap];
    navMiddleV.backgroundColor = [UIColor clearColor];
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, mScreenWidth-140, 32)];
    imageView.image = mImageByName(@"首页搜索框");
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [navMiddleV addSubview:imageView];
    self.navigationItem.titleView = navMiddleV;
    
    //处理点击推送启动app
    AppDelegate * app = mAppDelegate;
    if (app.pushInfo) {
        [AppPushHandleTool handlePushInfoForAppStart:app.pushInfo WithRootViewController:self];
    }
}
-(void)searchAction
{
    LLSearchViewController *seachVC = [[LLSearchViewController alloc] init];
    seachVC.hidesBottomBarWhenPushed = YES;
    seachVC.searchType = 1;
    [self.navigationController pushViewController:seachVC animated:YES];
}
#pragma mark - 主动退出登录
-(void)appOutLogin
{
    [self.tabBarController setSelectedIndex:0];
    [AppUserBaseModel deleateCashe];
    MDDLoginViewController * lvc = mGetStoryboardViewController(@"Main", @"mDDLoginViewController");
    lvc.isPush = YES;
    [self.navigationController pushViewController:lvc animated:YES];
    return;
}
#pragma mark -
#pragma mark - **************** collectionViewDelegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 4;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 1) {
        return self.homeKindItems.count;
    }
    if (section == 2) {
        return self.hasPlantCoupon?2:1;
    }
    if (section == 3) {//商品
        return self.remomGoodItems.count;
    }
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UICollectionViewCell * adCell = mGetCollectionViewCell(@"adCollectionCell", indexPath);
        [adCell addSubview:self.bannerView];
        [self.bannerView AxcUI_reloadData];
        return adCell;
    }else if (indexPath.section == 1){
        UICollectionViewCell * itemCellMoudle = mGetCollectionViewCell(@"itemCellMoudle", indexPath);
        HomeKindItem * item = self.homeKindItems[indexPath.row];
        UIImageView * iconBtn = mViewByTag(itemCellMoudle.contentView, 100, UIImageView);
//        [iconBtn setTitle:item.name forState:UIControlStateNormal];
        [iconBtn sd_setImageWithURL:[NSURL URLWithString:item.imageUrl] placeholderImage:mImageByName(@"")];
        UILabel * tLabel = mViewByTag(itemCellMoudle.contentView, 101, UILabel);
        tLabel.text = item.name;
        return itemCellMoudle;
        
    }else if (indexPath.section == 2){
        if (self.hasPlantCoupon) {
            if (indexPath.row == 0) {
                UICollectionViewCell * jiFenCCell = mGetCollectionViewCell(@"jiFenCCell", indexPath);
                return jiFenCCell;
            }
        }
        UICollectionViewCell * scrollItemCell = mGetCollectionViewCell(@"scrollItemCell", indexPath);
        [scrollItemCell.contentView addSubview:self.noticeView];
        return scrollItemCell;
    }else if (indexPath.section == 3){
        HomeGoodItemCCell * itemCellMoudle = mGetCollectionViewCell(@"homeGoodItemCCell", indexPath);
        itemCellMoudle.goodItem = self.remomGoodItems[indexPath.row];
        return itemCellMoudle;
    }
    return nil;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && indexPath.row == 0) {
        HomeKindItem * item = self.homeKindItems[indexPath.row];
        WXWebviewController * ttlvc = [[WXWebviewController alloc]init];
        ttlvc.urlString = item.url;
        ttlvc.hidesBottomBarWhenPushed = YES;
        NavigationController_pushVC(ttlvc);
    }
    if (indexPath.section == 1 && indexPath.row == 1) {
        TouTiaoListViewController * ttlvc = mGetStoryboardViewController(@"Main", @"touTiaoListViewController");
        NavigationController_pushVC(ttlvc);
    }
    if (indexPath.section == 1 && indexPath.row == 2) {
        MDDStoreViewController * ttlvc = mGetStoryboardViewController(@"Main", @"mDDStoreViewController");
        NavigationController_pushVC(ttlvc);
    }
    if (indexPath.section == 1 && indexPath.row == 3) {
        [AxcUI_Toast AxcUI_showCenterWithText:@"敬请期待"];
    }
    if (indexPath.section == 1 ) {
         HomeKindItem * item = self.homeKindItems[indexPath.row];
        if (item.type.integerValue == 4) {
            [self.tabBarController setSelectedIndex:1];
        }
    }
    if (indexPath.section == 2) {
        if (self.hasPlantCoupon && indexPath.row == 0) {
            ReceiveCouponViewController * rcvc = mGetStoryboardViewController(@"Main", @"receiveCouponViewController");
            NavigationController_pushVC(rcvc);
        }
    }
    if (indexPath.section == 3) {
        AppBaseGoodItem * goodItem = self.remomGoodItems[indexPath.row];
        MDDGoodsDetailViewController * detailVC = mGetStoryboardViewController(@"Main", @"mDDGoodsDetailViewController");
        detailVC.goodId = goodItem.gid;
        NavigationController_pushVC(detailVC);
    }
}
// 要先设置表头大小
- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGSizeMake(0, 0);
    }
    if (section == 1) {
        return CGSizeMake(0, 0);
    }
    if (section == 2) {
         return CGSizeMake(0, 0);
    }
    if (section == 3) {
        return CGSizeMake(mScreenWidth, 44);
    }
    return CGSizeMake(0, 0);
}

- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        if (indexPath.section == 0) {
            return nil;
        }
        if (indexPath.section == 3) {
            UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerCollectionView" forIndexPath:indexPath];
            UILabel * titleLabel = mViewByTag(headerView, 100, UILabel);
            titleLabel.text = @"热销商品";
            titleLabel.textColor = [UIColor AxcUI_colorWithHexColor:@"#6933DB"];
            UIView * view99 = mViewByTag(headerView, 99, UIView);
            UIView * view101 = mViewByTag(headerView, 101, UIView);
            view99.backgroundColor = [UIColor AxcUI_colorWithHexColor:@"#6933DB"];
            view101.backgroundColor = [UIColor AxcUI_colorWithHexColor:@"#6933DB"];

            
            return headerView;
        }
    }
    
    return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 ) {
        return CGSizeMake(mScreenWidth,mScreenWidth*150/345);
    }else if (indexPath.section == 1 ) {
        return CGSizeMake(mScreenWidth/4,mScreenWidth/4);
    }else if (indexPath.section == 2 ) {
        if (self.hasPlantCoupon) {
            if (indexPath.row == 0) {
                 return CGSizeMake(mScreenWidth,60);
            }
        }
        return CGSizeMake(mScreenWidth,44);
    }else if (indexPath.section == 3 ) {
        return CGSizeMake((mScreenWidth-45)/2,(mScreenWidth-45)*0.5+70);
    }else{
        return CGSizeMake(0, 0);
    }
    
}
//这个是两行cell之间的间距（上下行cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 0 ) {
        return 0;
    }else if (section == 1 ) {
        return 0;
    }else if (section == 2 ) {
        return 0;
    }else if (section == 3 ) {
        return 15;
    }else{
        return 12;
    }
}
//两个cell之间的间距（同一行的cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 0 ) {
        return 0;
    }else if (section == 1 ) {
        return 0;
    }else if (section == 2 ) {
        return 0;
    }else if (section == 3 ) {
        return 15;
    }else{
        return 12;
    }
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (section == 0 ) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }else if (section == 1 ) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }else if (section == 2 ) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }else if (section == 3 ) {
        return UIEdgeInsetsMake(0, 15, 0, 15);
    }else{
        return UIEdgeInsetsMake(12, 12, 12, 12);
    }
}
#pragma mark AxcBannerViewDataSource
// 返回 Banner 需要显示 Item(View) 的个数
- (NSInteger)AxcUI_numberOfItemsInBanner:(AxcUI_BannerView *)banner{
    return self.bannerList.count;
}

// 返回 Banner 在不同的 index 所要显示的 View (可以是完全自定义的v iew, 且无需设置 frame)
- (UIView *)AxcUI_banner:(AxcUI_BannerView *)banner viewForItemAtIndex:(NSInteger)index{
//    AppADModel * model = self.bannerList[index];
    NSString *imageName = [self.bannerList[index] imageUrl];
    // 创建将要显示控件
    UIImageView *imageView = [[UIImageView alloc] init];
    // 加载图片，返回任意View即可，这里使用网络加载图片展示简单轮播
    [imageView sd_setImageWithURL:[NSURL URLWithString:imageName] placeholderImage:nil];
    
//    imageView.contentMode = UIViewContentModeScaleAspectFill;
    
    return imageView;
}
// 当self.bannerView.axcUI_showFooter = YES 的时候才会回调这个委托
- (void)AxcUI_bannerFooterDidTrigger:(AxcUI_BannerView *)banner{
    NSLog(@"触发了footer");
    
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view.backgroundColor = [UIColor AxcUI_CloudColor];
    vc.title = @"新测试VC";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)AxcUI_banner:(AxcUI_BannerView *)banner didSelectItemAtIndex:(NSInteger)index{
    NSLog(@"点击了第%zi个View",index);
    HomeADItem * adItem = self.bannerList[index];
    if (adItem.type.integerValue == 0) {//h5链接
        WXWebviewController * ttlvc = [[WXWebviewController alloc]init];
        ttlvc.urlString = adItem.url;
        ttlvc.hidesBottomBarWhenPushed = YES;
        NavigationController_pushVC(ttlvc);
    }else if (adItem.type.integerValue == 2){//商品
        MDDGoodsDetailViewController * gdvc = mGetStoryboardViewController(@"Main", @"mDDGoodsDetailViewController");
        gdvc.goodId = adItem.url;
        NavigationController_pushVC(gdvc);
    }else if (adItem.type.integerValue == 1){//店铺
        StoreDetailViewController * gdvc = mGetStoryboardViewController(@"Main", @"storeDetailViewController");
        gdvc.storeId = adItem.url;
        NavigationController_pushVC(gdvc);
    }
}

// 返回 Footer 在不同状态时要显示的文字
- (NSString *)AxcUI_banner:(AxcUI_BannerView *)banner titleForFooterWithState:(AxcBannerFooterState)footerState{
    if (footerState == AxcBannerFooterStateIdle) {
        return @"拖动进入下一页";
    } else if (footerState == AxcBannerFooterStateTrigger) {
        return @"释放进入下一页";
    }
    return nil;
}
#pragma mark - 懒加载区
- (AxcUI_BannerView *)bannerView{
    if (!_bannerView) {
        _bannerView = [[AxcUI_BannerView alloc] initWithFrame:CGRectMake(0, 0, mScreenWidth, mScreenWidth*150/345)];
        _bannerView.axcUI_bannerDataSource = self;
        _bannerView.axcUI_bannerDelegate = self;
        _bannerView.axcUI_shouldLoop = YES;
        _bannerView.axcUI_autoScroll = YES;
        // 设置frame
    }
    return _bannerView;
}
- (NSMutableArray *)bannerList{
    if (!_bannerList) {
//        _bannerList = @[@"http://pic.58pic.com/58pic/13/88/95/27p58PICWau_1024.jpg",
//                       @"http://images.missyuan.com/attachments/day_080414/20080414_5651a9ad503e6852ae9e6GVhuTdhVFAc.jpg",
//                       @"http://pic28.nipic.com/20130424/11588775_115415688157_2.jpg",
//                       @"http://ww4.sinaimg.cn/bmiddle/62faf073jw1ds4rt49wbqg.gif"];
        _bannerList = [[NSMutableArray alloc]init];
    }
    return _bannerList;
}
#pragma mark -
#pragma mark - **************** 数据请求
-(void)loadHomeADdata
{
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
    [PPNetworkHelper POST:app_home_ad parameters:parameters success:^(id responseObject) {
        if (YJPPSUCCESS(responseObject)) {
            for (NSDictionary * dataD in responseObject[@"data"]) {
                HomeADItem * item = [[HomeADItem alloc]init];
                [item setValuesForKeysWithDictionary:dataD];
                [self.bannerList addObject:item];
            }
            [self.bannerView AxcUI_reloadData];
        }else{
            
        }
    } failure:^(NSError *error) {
        
    } showLoading:nil];
}
#pragma mark -
#pragma mark - **************** 查询是否有优惠券
-(void)loadHadCounpon
{
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
    [PPNetworkHelper POST:app_coupon_hasPlantCoupon parameters:parameters success:^(id responseObject) {
        if (YJPPSUCCESS(responseObject)) {
            if ([responseObject[@"data"][@"hasCoupon"] integerValue ] == 0) {
                self.hasPlantCoupon = YES;
            }else{
                self.hasPlantCoupon = NO;
            }
        }else{
            
        }
        [self.selfCollectionView reloadData];
    } failure:^(NSError *error) {
        
    } showLoading:nil];
}

-(void)loadHomeKinds
{
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
    [PPNetworkHelper POST:app_home_tab parameters:parameters success:^(id responseObject) {
        if (YJPPSUCCESS(responseObject)) {
            for (NSDictionary * dataD in responseObject[@"data"]) {
                HomeKindItem * item = [[HomeKindItem alloc]init];
                [item setValuesForKeysWithDictionary:dataD];
                [self.homeKindItems addObject:item];
            }
            [self.selfCollectionView reloadData];
        }else{
            
        }
    } failure:^(NSError *error) {
        
    } showLoading:nil];
}
-(void)loadHomeRemmendGoods
{
    if ([self.selfCollectionView.mj_header isRefreshing]) {
        self.page = 1;
    }
    if ([self.selfCollectionView.mj_footer isRefreshing]) {
        self.page ++;
    }
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
    setDickeyobj(parameters, @"10", @"limit");
    NSString * pageStr = [NSString stringWithFormat:@"%ld",self.page];
    setDickeyobj(parameters, pageStr, @"page");
    [PPNetworkHelper POST:app_home_rmdGoods parameters:parameters success:^(id responseObject) {
        [self.selfCollectionView.mj_header endRefreshing];
        [self.selfCollectionView.mj_footer endRefreshing];
        if (self.page == 1 && self.remomGoodItems.count > 0) {
            [self.remomGoodItems removeAllObjects];
        }
        if (YJPPSUCCESS(responseObject)) {
            for (NSDictionary * dataD in responseObject[@"data"][@"rmdGoods"][@"list"]) {
                AppBaseGoodItem * item = [[AppBaseGoodItem alloc]init];
                [item setValuesForKeysWithDictionary:dataD];
                [self.remomGoodItems addObject:item];
            }
            if ([responseObject[@"data"][@"rmdGoods"][@"list"] count] < 10) {
                [self.selfCollectionView.mj_footer endRefreshingWithNoMoreData];
            }
        }else{
            
        }
        [self.selfCollectionView reloadData];
    } failure:^(NSError *error) {
        [self.selfCollectionView.mj_header endRefreshing];
        [self.selfCollectionView.mj_footer endRefreshing];
    } showLoading:nil];
}
-(void)loadHomeOrderScroll
{
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
    [PPNetworkHelper POST:app_home_orderMsg parameters:parameters success:^(id responseObject) {
        
        if (YJPPSUCCESS(responseObject)) {
            for (NSDictionary * dataD in responseObject[@"data"]) {
                [self.noticeArr addObject:dataD];
            }
            [self.noticeView beginScroll];
        }else{
            
        }
    } failure:^(NSError *error) {
        
    } showLoading:nil];
}
-(NSMutableArray *)noticeArr
{
    if (!_noticeArr) {
        _noticeArr = [[NSMutableArray alloc]init];
    }
    return _noticeArr;
}
-(GYRollingNoticeView *)noticeView
{
    if (!_noticeView) {
        _noticeView = [[GYRollingNoticeView alloc]initWithFrame:CGRectMake(65, 0, mScreenWidth-50, 45)];
        _noticeView.dataSource = self;
        _noticeView.delegate = self;
        [_noticeView registerClass:[GYNoticeViewCell class] forCellReuseIdentifier:@"GYNoticeViewCell"];
    }
    return _noticeView;
}
- (NSInteger)numberOfRowsForRollingNoticeView:(GYRollingNoticeView *)rollingView
{
    
    return self.noticeArr.count;
}
- (__kindof GYNoticeViewCell *)rollingNoticeView:(GYRollingNoticeView *)rollingView cellAtIndex:(NSUInteger)index
{
    GYNoticeViewCell *cell = [rollingView dequeueReusableCellWithIdentifier:@"GYNoticeViewCell"];
    NSString * phone = [NSString stringWithFormat:@"%@****%@",[self.noticeArr[index][@"phone"] substringWithRange:NSMakeRange(0, 4)],[self.noticeArr[index][@"phone"] substringWithRange:NSMakeRange(0, 4)]];
    NSString * name = [NSString stringWithFormat:@"%@**",[self.noticeArr[index][@"contactName"] substringWithRange:NSMakeRange(0, 1)]];
    cell.textLabel.text = [NSString stringWithFormat:@"%@        %@          下单了",phone,name];
//    cell.logoImageView.image = mImageByName(@"正在下单.jpg");
//    cell.logoImageView.hidden = YES;
    //    [cell.logoImageView sd_setImageWithURL:[NSURL URLWithString:self.noticeArr[index][@"imgUrl"]] placeholderImage:mImageByName(@"xiaofang")];
    return cell;
}
- (void)didClickRollingNoticeView:(GYRollingNoticeView *)rollingView forIndex:(NSUInteger)index
{
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
